<script lang="ts" setup>
import type { BaseRoleModel } from '#/api/basic/system/model/baseRoleModel';

import { onMounted, reactive, ref, unref } from 'vue';

import { ColPage } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import { useLoading } from '@vben-core/shadcn-ui';

import { useFs } from '@fast-crud/fast-crud';
import { Button, Tooltip } from 'ant-design-vue';

import { BaseRoleConfig } from '#/api/basic/system/baseRole';
import { getValidateRulesByFs } from '#/api/common/validateByFs';
import { ActionEnum } from '#/enums/commonEnum';
import BindEmployee from '#/views/_core/common/bindEmployee/index.vue';

import { createCrudOptions, frontRules } from './data/crud';
import ApplicationTrees from './modules/application-trees.vue';

defineOptions({
  name: '角色管理',
  inheritAttrs: false,
});
const colPageProps = reactive({
  leftCollapsedWidth: 3,
  // 左侧最大宽度百分比
  leftMaxWidth: 50,
  // 左侧最小宽度百分比
  leftMinWidth: 10,
  // 左侧默认宽度
  leftWidth: 50,
  // 右侧默认宽度
  rightWidth: 50,
  // 左侧可折叠
  leftCollapsible: true,
  // 显示拖动手柄
  splitHandle: true,
  // 可拖动调整宽度
  resizable: true,
  // 显示拖动分隔线
  splitLine: true,
});
const bindEmployeeRef = ref<any>(null);
const treeRef = ref<any>(null);
const [openFullLoading, closeFullLoading] = useLoading({
  text: '加载中...',
});

async function select(role: BaseRoleModel.BaseRoleResultVO) {
  try {
    openFullLoading();

    await getTreeRef().load(role);
  } finally {
    closeFullLoading();
  }
}

const { crudRef, crudBinding, crudExpose, appendCrudOptions } = useFs({
  createCrudOptions,
  context: { select, treeRef, bindEmployeeRef },
});

function getTreeRef() {
  return unref(treeRef);
}

// 页面打开后获取列表数据
onMounted(async () => {
  const addFormOptions = await getValidateRulesByFs({
    Api: BaseRoleConfig.Save,
    mode: ActionEnum.ADD,
    customRules: frontRules(crudExpose, ActionEnum.ADD),
    trigger: ['blur', 'change'],
  });
  const editFormOptions = await getValidateRulesByFs({
    Api: BaseRoleConfig.Update,
    mode: ActionEnum.EDIT,
    customRules: frontRules(crudExpose, ActionEnum.EDIT),
    trigger: ['blur', 'change'],
  });
  appendCrudOptions({ ...addFormOptions, ...editFormOptions });
  crudExpose.doRefresh();
});
</script>

<template>
  <ColPage v-bind="colPageProps">
    <template #left="{ isCollapsed, expand }">
      <div v-if="isCollapsed" @click="expand">
        <Tooltip title="点击展开左侧">
          <Button shape="circle" type="primary">
            <template #icon>
              <IconifyIcon class="text-2xl" icon="bi:arrow-right" />
            </template>
          </Button>
        </Tooltip>
      </div>
      <div
        v-else
        class="border-border bg-card mr-1 h-full rounded-[var(--radius)] border px-1"
      >
        <FsCrud ref="crudRef" v-bind="crudBinding" />
      </div>
    </template>
    <ApplicationTrees ref="treeRef" v-bind="crudBinding" />
    <BindEmployee ref="bindEmployeeRef" v-bind="crudBinding" />
  </ColPage>
</template>
